extends Node2D

@onready var camera_2d: Camera2D = $Camera2D
@onready var bird: RigidBody2D = $Bird
@onready var backgrounds: Node2D = $Backgrounds
@onready var pipes: Node2D = $Pipes

signal end_game(point:int)

var pipeInterval:int=150
var pipeCount:int=3

func _ready() -> void:
	#以当前小鸟位置，每隔pipeInterval间距生成水管
	for i in range(30):
		createPipe()
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	#移动相机
	camera_2d.position.x=bird.position.x-300
	#移动多收个背景
	var count=int(bird.position.x)/1152
	backgrounds.position.x=count*1152
	#血量小于0结束游戏
	if(bird.hp<=0):
		emit_signal("end_game",bird.point)
	pass

func createPipe() -> void:
	var createPositionX=pipeCount*pipeInterval
	var createPositionY=randf_range(80,320)
	
	var pipeResource=preload("res://scene/Pipe.tscn")
	var newPipe=pipeResource.instantiate()
	newPipe.position.x=createPositionX
	newPipe.position.y=createPositionY
	newPipe.name=String.num_int64(pipeCount)
	pipes.add_child(newPipe)
	
	newPipe.get_node("VisibleOnScreenNotifier2D").screen_exited.connect(onPipeScreenExited.bind(newPipe))
	newPipe.get_node("Coin").connect("body_entered",Callable(self,"onBirdEntered"))
	
	pipeCount+=1
	pass

func onPipeScreenExited(exitedPipe:Node2D):
	exitedPipe.queue_free()
	createPipe()
	pass
	
func onBirdEntered(other_body):
	if other_body==bird:
		$Bird/Point.play()
		$Bird.point+=1
	pass
